package com.lagou.service.dubbo;

import com.lagou.dao.CodeDao;
import com.lagou.pojo.Code;
import com.lagou.service.CodeDubboService;
import com.lagou.service.IMessageDubboService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.List;
import java.util.Random;

@Service
public class CodeDubboServiceImpl implements CodeDubboService {
    @Autowired
    CodeDao codeDao;

    @Reference
    IMessageDubboService iMessageService;

    @Override
    public boolean create(String email) {
        int flag = new Random().nextInt(999999);
        if (flag < 100000)
        {
            flag += 100000;
        }
        Code code = new Code();
        code.setCode(String.valueOf(flag));
        code.setEmail(email);
        code.setCreatetime(System.currentTimeMillis());
        code.setExpiretime(System.currentTimeMillis()+10*60000);
        Code save = codeDao.save(code);
        boolean sendmail = iMessageService.sendmail(email, String.valueOf(flag));
        return sendmail;
    }

    @Override
    public Integer validate(String email, String code) {
        Code code1 = new Code();
        code1.setEmail(email);
        code1.setCode(code);
        Example<Code> codeExample = Example.of(code1);
        List<Code> codeList = codeDao.findAll(codeExample);
        if (codeList.size()==0){
            //验证码错误
            return 1;
        }
        codeList.sort((o1,o2)->{
            Long expiretime = o1.getExpiretime()- o2.getExpiretime();
            return expiretime.intValue();
        });
        System.out.println(codeList.get(0).getExpiretime()+"==================================");
        long time = codeList.get(0).getExpiretime() - System.currentTimeMillis();
        if(time>0){
            //正确
            return 0;
        }
        //超时
        return 2;
    }
}
